import time

from captcha.image import ImageCaptcha
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render
from rest_framework.views import APIView,Response
from rest_framework import status

from .models import *
from .serializer import *

from utils.jwt_token import _generate_token

import random
import redis,string


# 生成图片验证码
class Image(APIView):
    def get(self,request, uuid):
        # 生成随机字符串
        code_str = "".join(random.sample(string.ascii_letters + string.digits, 4))
        print("字符码:", code_str)

        # 存储随机字符串
        redis_conn = redis.Redis(host="localhost", port=6379, db=0,)
        key = "imageCode:%s"%uuid
        redis_conn.set(key, code_str, ex=300)
        redis_conn.close()

        # 图片验证码
        captcha_obj = ImageCaptcha()
        image_captcha = captcha_obj.generate(code_str)  # BytesIO对象， 类似于文件对象

        print(image_captcha)

        return HttpResponse(image_captcha, content_type="image/png")

# 登录
class Login(APIView):
    def post(self,request):
        account = request.data.get('account')
        password = request.data.get('password')
        img_code = request.data.get('img_code')
        uuid = request.data.get('uuid')
        print('>>>',uuid,img_code)
        redis_conn = redis.Redis(host="localhost", port=6379, db=0, )
        key = "imageCode:%s" % uuid
        img = redis_conn.get(key)
        if not img :
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'验证码过期'})
        if not img.decode().lower() == img_code.lower():
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'验证码错误'})
        user = UserModel.objects.get(account=account)
        if not user:
            return Response({'code': status.HTTP_204_NO_CONTENT, 'msg': '用户不存在'})
        user = UserModel.objects.get(account=account, password=password)
        if user:
            data = {
                'user_id': user.id,
                'user_name': user.username,
                'role':user.role_id,
            }
            token,refresh_token = _generate_token(data)
            return Response({'code': status.HTTP_200_OK, 'msg': '登录成功', 'token': token,'refresh_token':refresh_token,'id':user.id})
        return Response({'code': status.HTTP_204_NO_CONTENT, 'msg': '密码错误'})


# 菜单
class MenuBarViews(APIView):
    def get(self, request):
        user = request.session.get('user')
        role_id = user['role']
        # print(uid)
        role = RoleModel.objects.get(id=role_id)
        rolemenu= RoleMenuModel.objects.filter(role_id=role.id).all()
        # rolemenu_ser = RoleMenuSer(rolemenu,many=True).data
        data = []
        for t in rolemenu:
            print(t.menu_id)
            menus = MenuModel.objects.filter(assoc_id=None,id=t.menu_id).all()
            menus_ser = MenuSer(menus, many=True).data

            for i in menus_ser:
                # 获取父级下的所有子级
                menus2 = MenuModel.objects.filter(assoc_id=i['id']).all()
                menus2_ser = MenuSer(menus2, many=True).data
                i['submenus'] = menus2_ser
                data.append(i)

        return Response({'msg': '获取角色菜单成功', 'code': status.HTTP_200_OK, 'data': data })

# 校长
class Headmaster(APIView):
    def post(self,request):
        username = request.data.get('username')
        account = request.data.get('account')
        password = request.data.get('password')
        phone = request.data.get('phone')
        age = request.data.get('age')
        # gender = request.data.get('gender')
        # print('AAAAAA',gender)
        user = UserModel.objects.filter(account=account).first()
        if user:
            return Response({'code':status.HTTP_204_NO_CONTENT, 'msg': '该账号已存在'})

        # if gender == '男':
        #     gender = 1
        # elif gender == '女':
        #     gender = 2
        # UserModel.objects.create(username=username,account=account,password=password,phone=phone,age=age,gender=gender,role_id=2)
        UserModel.objects.create(username=username,account=account,password=password,phone=phone,age=age,role_id=2)
        return Response({'code':status.HTTP_200_OK,'msg':'创建校长成功'})

    def get(self,reqeust):
        user = UserModel.objects.filter(role_id=2).all()
        userSer = UserSer(user,many=True).data

        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':userSer})

# 获取单个校长信息
class HeadmasterAPI(APIView):
    def get(self,request,pk):
        user = UserModel.objects.get(Q(id=pk) & Q(role_id=2))
        userSer = UserSer(user).data

        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': userSer})

    def put(self,request,pk):
        username = request.data.get('username')
        account = request.data.get('account')
        password = request.data.get('password')
        phone = request.data.get('phone')
        age = request.data.get('age')
        gender = request.data.get('gender')

        if gender == '男':
            gender = 1
        elif gender == '女':
            gender = 2

        user = UserModel.objects.filter(Q(id=pk)&Q(role_id=2))
        if not user:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该校长不存在'})
        user.update(username=username,account=account,password=password,phone=phone,age=age,gender=gender,role_id=2)
        return Response({'code':status.HTTP_200_OK,'msg':'修改校长信息成功'})



# 学校
class School(APIView):
    def post(self,request):
        s_name = request.data.get('s_name')
        user = request.data.get('user')

        school = SchoolModel.objects.filter(s_name=s_name).first()
        if school:
            return Response({'code':status.HTTP_204_NO_CONTENT,'msg':'该学校已存在'})
        use = UserModel.objects.filter(id=user).first()
        if not use:
            return Response({'code':status.HTTP_204_NO_CONTENT,'msg':'没有该校长'})
        SchoolModel.objects.create(s_name = s_name,user_id = user)
        return Response({'code':status.HTTP_200_OK,'msg':'创建成功'})


    def get(self,request):
        school = SchoolModel.objects.all()
        schoolSer = SchoolSer(school,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':schoolSer})


# 单个学校
class Single_School(APIView):
    def get(self,request,pk):
        school = SchoolModel.objects.filter(id=pk).first()
        schoolSer = SchoolSer(school).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取单个学校成功','data':schoolSer})

    def put(self,request,pk):
        s_name = request.data.get('s_name')
        user = request.data.get('user')

        school = SchoolModel.objects.filter(id=pk)
        if not school:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'没有该学校'})

        school.update(s_name=s_name,user_id=user)
        return Response({'code':status.HTTP_200_OK,'msg':'修改成功'})



# 老师
class Teacher(APIView):
    def post(self, request):
        username = request.data.get('username')
        account = request.data.get('account')
        password = request.data.get('password')
        phone = request.data.get('phone')
        age = request.data.get('age')
        gender = request.data.get('gender')

        user = request.session.get('user')
        uid = user['user_id']

        school = SchoolModel.objects.filter(user_id=uid).first()
        user = UserModel.objects.filter(account=account).first()
        if user:
            return Response({'code': status.HTTP_204_NO_CONTENT, 'msg': '该账号已存在'})

        if gender == '男':
            gender = 1
        elif gender == '女':
            gender = 2
        UserModel.objects.create(username=username, account=account, password=password, phone=phone, age=age,
                                 gender=gender, role_id=3)
        users = UserModel.objects.get(account=account)
        TeachersModel.objects.create(user_id=users.id,school_id=school.id)
        return Response({'code': status.HTTP_200_OK, 'msg': '创建老师成功'})



# 学校老师
class Teacher_School(APIView):
    def get(self,request):
        user = request.session.get('user')
        uid = user['user_id']

        school = SchoolModel.objects.get(user_id=uid)
        teacher = TeachersModel.objects.filter(school_id = school.id).all()
        teacherSer = TeachersSer(teacher,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取该学校老师成功','data':teacherSer})



# 修改老师信息
class TeacherAPi(APIView):
    def get(self,rquest,pk):
        teacher = TeachersModel.objects.get(id=pk)
        user = UserModel.objects.filter(Q(id=teacher.user_id) & Q(role_id=3)).first()
        userSer = UserSer(user).data
        teacherSer = TeachersSer(teacher).data
        userSer['school'] = teacherSer['school']
        userSer['school_name'] = teacherSer['school_name']
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':userSer})

    def put(self,request,pk):
        username = request.data.get('username')
        account = request.data.get('account')
        password = request.data.get('password')
        phone = request.data.get('phone')
        age = request.data.get('age')
        gender = request.data.get('gender')

        if gender == '男':
            gender = 1
        elif gender == '女':
            gender = 2
        user = UserModel.objects.filter(Q(id=pk) & Q(role_id=3))
        if not user:
            return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该老师不存在'})
        user.update(username=username, account=account, password=password, phone=phone, age=age,
                                 gender=gender, role_id=3)
        return Response({'code': status.HTTP_200_OK, 'msg': '修改老师信息成功'})


# 班级
class Cls(APIView):
    def post(self,request):
        c_name = request.data.get('c_name')
        user = request.data.get('user')

        users = request.session.get('user')
        uid = users['user_id']

        school = SchoolModel.objects.filter(user_id=uid).first()

        use = UserModel.objects.filter(Q(id=user) & Q(role_id=3)).first()
        if not use:
            return Response({'code': status.HTTP_204_NO_CONTENT, 'msg': '没有该老师'})

        teacher = TeachersModel.objects.filter(Q(user_id=user)&Q(school_id=school.id)).first()
        if not teacher:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该老师不是本学校的人'})

        cla = ClassModel.objects.filter(Q(c_name=c_name)&Q(school_id=school.id)).first()
        if cla:
            return Response({'code':status.HTTP_204_NO_CONTENT,'msg':'该班级已存在'})

        ClassModel.objects.create(c_name = c_name,teacher_id = user,school_id=school.id)
        return Response({'code':status.HTTP_200_OK,'msg':'创建班级成功'})


    def get(self,request):
        users = request.session.get('user')
        uid = users['user_id']
        school = SchoolModel.objects.get(user_id=uid)
        cls = ClassModel.objects.filter(school_id = school.id).all()
        clsSer = ClassSer(cls,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':clsSer})


#获取老师管理的所有班级
class cals(APIView):
    def get(self,request):
        users = request.session.get('user')
        uid = users['user_id']

        cls = ClassModel.objects.filter(teacher_id=uid).all()
        clazer = ClassSer(cls,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':clazer})



# 新增学生
class Students(APIView):
    def post(self, request):
        username = request.data.get('username')
        account = request.data.get('account')
        password = request.data.get('password')
        phone = request.data.get('phone')
        age = request.data.get('age')
        gender = request.data.get('gender')
        cla = request.data.get('cla')

        user = UserModel.objects.filter(account=account).first()
        if user:
            return Response({'code': status.HTTP_204_NO_CONTENT, 'msg': '该账号已存在'})

        if gender == '男':
            gender = 1
        elif gender == '女':
            gender = 2
        UserModel.objects.create(username=username, account=account, password=password, phone=phone, age=age,
                                 gender=gender, role_id=4)
        users = UserModel.objects.get(account=account)
        StudentsModel.objects.create(user_id=users.id,cla_id=cla)
        return Response({'code': status.HTTP_200_OK, 'msg': '创建学生成功'})


# 获取班级的学生
class Cla_Student(APIView):
    def get(self,request,pk):
        student = StudentsModel.objects.filter(cla_id=pk).all()
        studentSer = StudentsSer(student,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取该班级下所有学生成功','data':studentSer})



# 问候语
class GreetingsView(APIView):
    def get(self, request):
        try:
            t = time.localtime()
            current_time = time.strftime("%H:%M:%S", t)
            print(current_time)
            ls=[]
            list = Greetings.objects.filter(Q(start_time__lte=str(current_time)) & Q(end_time__gte=str(current_time))).all()
            # print(list.query)  # 查看原生sql语句
            for i in list:
                ls.append(i.id)
            a = random.choice(ls)
            greet = Greetings.objects.get(id=a)
            return Response({"code": status.HTTP_200_OK, "msg": "成功",'data':greet.content})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})



# 分类
class SortAPI(APIView):
    def post(self,request):
        s_name = request.data.get('s_name')

        sort = Sort.objects.filter(s_name = s_name).first()
        if sort:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该类型已存在'})

        Sort.objects.create(s_name = s_name)
        return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})

    def get(self,request):
        sort = Sort.objects.all()
        sortzer = SortSer(sort,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':sortzer})


# 标签
class LabelAPI(APIView):
    def post(self,request):
        l_name = request.data.get('l_name')

        label =Label.objects.filter(l_name = l_name).first()
        if label:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该类型已存在'})

        Label.objects.create(l_name = l_name)
        return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})

    def get(self,request):
        label = Label.objects.all()
        labelzer = LabelSer(label,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':labelzer})

# 学习内容
class Learning_contentAPI(APIView):
    def post(self,request):
        title = request.data.get('title')
        c_name = request.data.get('c_name')
        introduction = request.data.get('introduction')
        is_open = request.data.get('is_open')
        sort = request.data.get('sort')
        label = request.data.get('label')

        users = request.session.get('user')
        uid = users['user_id']

        learn = Learning_content.objects.filter(title=title).first()
        if learn:
            return Response({"code":status.HTTP_400_BAD_REQUEST,'msg':"该标题已存在"})

        Learning_content.objects.create(title=title,c_name=c_name,introduction=introduction,is_open=is_open,user_id=uid)
        learn = Learning_content.objects.get(title=title)
        sor = sort.split(',')
        lab = label.split(',')
        for i in sor:
            Learning_Sort.objects.create(learning_id=learn.id,sort_id=i)

        for i in lab:
            Learning_Label.objects.create(learning_id=learn.id,label_id=i)

        return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})

    def get(self,request):
        lear = Learning_content.objects.filter(is_open = 1).all()
        learSer = Learning_contentSer(lear,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':learSer})


# 获取单个学习内容
class ContentAPI(APIView):
    def get(self,request,pk):
        lear = Learning_content.objects.filter(id=pk).first()
        learSer = Learning_contentSer(lear).data
        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': learSer})


# 获取我发布的学习内容
class Learning_Content(APIView):
    def get(self,request):
        users = request.session.get('user')
        uid = users['user_id']

        lear = Learning_content.objects.filter(user_id=uid).all()
        learSer = Learning_contentSer(lear, many=True).data
        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': learSer})



# 资源
class Resources(APIView):
    def post(self,request):
        r_name = request.data.get('r_name')
        describe = request.data.get('describe')
        price = request.data.get('price')
        img = request.data.get('img')

        users = request.session.get('user')
        uid = users['user_id']

        resou = Resource.objects.filter(r_name=r_name).first()
        if resou:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该资源已存在'})

        Resource.objects.create(r_name=r_name,describe=describe,price=price,user_id=uid,img=img)
        return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})

    def get(self,request):
        resou = Resource.objects.all()
        resouSer = ResourceSer(resou,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':resouSer})

# 获取单个资源
class ResourceAPI(APIView):
    def get(self,request,pk):
        resou = Resource.objects.filter(id=pk).first()
        resouSer = ResourceSer(resou).data
        return Response({"code":status.HTTP_200_OK,'msg':'获取成功','data':resouSer})

    def post(self,request,pk):
        title = request.data.get('title')
        is_free = request.data.get('is_free')

        users = request.session.get('user')
        uid = users['user_id']
        resou = Resource.objects.get(id=pk)
        if resou.user_id !=uid:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'您不是该资源的作者，添加不了章节'})

        ChaptersModel.objects.create(title=title,resource_id=pk,is_free=is_free)
        return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})

# 获取章节
class Chapters(APIView):
    def get(self,request,pk):
        chap = ChaptersModel.objects.filter(resource_id=pk).all()
        chapSer = ChaptersSer(chap,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':chapSer})


# 添加小节
class Sections(APIView):
    def post(self,reqeust):
        title = reqeust.data.get('title')
        content = reqeust.data.get('content')
        chapter = reqeust.data.get('chapter')

        sect = SectionsModel.objects.filter(chapter_id=chapter).first()
        if sect:
            if sect.title == title:
                return Response({"code":status.HTTP_400_BAD_REQUEST,'msg':'该章节下已有该小节'})
        SectionsModel.objects.create(title=title,content=content,chapter_id=chapter)
        return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})


class SectionsAPI(APIView):
    def get(self,request,pk):
        sect = SectionsModel.objects.filter(chapter_id=pk).all()
        sectSer = SectionsSer(sect,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':sectSer})




# 添加学习任务
class LearnTask(APIView):
    def post(self,request):
        remark = request.data.get('remark')
        content = request.data.get('content')
        classs = request.data.get('classs')

        users = request.session.get('user')
        uid = users['user_id']
        learn = LearnTaskModel.objects.filter(classs_id=classs).first()
        if learn:
            lear_task = Learning_TaskModel.objects.filter(task_id=learn.id).all()
            for i in lear_task:
                if int(i.content_id) == int(content):
                    return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该班级内已有该内容'})

            learn = LearnTaskModel.objects.filter(classs_id=classs).first()
            Learning_TaskModel.objects.create(task_id=learn.id, content_id=content)

            return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})

        LearnTaskModel.objects.create(remark=remark,classs_id=classs,operator_id=uid)
        learn = LearnTaskModel.objects.filter(classs_id=classs).first()
        Learning_TaskModel.objects.create(task_id=learn.id,content_id=content)

        return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})

# 获取班级下的任务
class Task(APIView):
    def get(self,request,pk):
        learn = LearnTaskModel.objects.filter(classs_id=pk).first()
        if not learn:
            return Response({'code':status.HTTP_204_NO_CONTENT,'msg':'该班级下还没任务'})

        lear_task = Learning_TaskModel.objects.filter(task_id=learn.id).all()
        lear_task_Ser = Learning_TaskSer(lear_task,many=True).data
        return Response({"code":status.HTTP_200_OK,'msg':'获取成功','data':lear_task_Ser})



# 评论（内容和用户， 回复（用户和））
class CommentsView(APIView):
    # 发送评论和回复
    def post(self, request):
        common_content = request.data.get('common_content')
        content= request.data.get('content')
        parent_id = request.data.get('parent_id')

        users = request.session.get('user')
        uid = users['user_id']

        if not parent_id:
            Comment.objects.create(user_id=uid, common_content=common_content,content_id=content,is_reply=False)
            return Response({'code': 200, 'msg': '发布评论成功'})
        else:
            Comment.objects.create(user_id=uid, content_id=content,
                                   is_reply=True, parent_id_id=parent_id)
            comm = Comment.objects.get(id=parent_id)
            comm.update(reply_count=int(comm.reply_count)+1)
            return Response({'code': 200, 'msg': '回复评论成功'})

# 查看评论
class CommentViewsTow(APIView):

    def get(self, request, id):
        try:
            observer = Comment.objects.filter(content_id=id).all()
            observer_ser = CommentSer(observer,many=True).data
            lst = []
            for i in observer_ser:
                print(i.get("id"))
                print(i)
                obse_all = Comment.objects.filter(parent_id_id=i.get("id")).all()
                obse_all_ser = CommentSer(obse_all, many=True).data
                lst.append(obse_all_ser)
                observer_ser['obse'] = lst
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':observer_ser})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "错误"})

# 收藏
class CollectView(APIView):
    def post(self, request):
        try:
            user = request.data.get("user")
            count = request.data.get("count")
            print("接受的数据",request.data)

            user_id = UserModel.objects.get(user_name=user).id
            count_id = Learning_content.objects.get(learning_content_name=count).id

            collect = CollectModel.objects.filter(user=user_id,content=count_id).first()
            collect_ser = Learning_contentSer(collect).data
            print(collect)
            print(collect_ser)
            if collect != None:
                if collect_ser.get("is_collect") == 0:
                    CollectModel.objects.filter(user_id=user_id,content_id=count_id).update(is_collect=1)
                    is_collect = True
                    return Response({"code": status.HTTP_200_OK,"msg": "收藏成功","data": is_collect})
                else:
                    CollectModel.objects.filter(user_id=user_id,content_id=count_id).update(is_collect=0)
                    is_collect = False
                    return Response({"code": status.HTTP_200_OK,"msg": "取消收藏成功","data": is_collect})
            else:
                CollectModel.objects.create(user_id=user_id,content_id=count_id,is_collect=1)
                is_collect = True
                return Response({"code": status.HTTP_200_OK,"msg": "收藏成功","data": is_collect})
        except Exception as e:
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":'数据错误或服务器错误'})

# 点赞
class TasnfView(APIView):
    def post(self,request):
        comment = request.data.get('comment')

        users = request.session.get('user')
        uid = users['user_id']
        like = LikeModel.objects.filter(Q(user_id=uid)&Q(comment_id=comment)).first()
        if like:
            like.delete()
            comm = Comment.objects.filter(id=comment).first()
            comm.like_count-=1
            comm.save()
            return Response({'code':status.HTTP_200_OK,'msg':'取消点赞成功'})
        else:
            LikeModel.objects.create(user_id=uid,comment_id=comment)
            comm = Comment.objects.filter(id=comment).first()
            comm.like_count+=1
            comm.save()
            return Response({'code': status.HTTP_200_OK, 'msg': '点赞成功'})



# 自动获取文章标签
from aip import AipNlp
import json
from tornado.escape import json_decode
class Voluntarily(APIView):

    def __init__(self):
        self.appId = '27632950'
        self.apiKey = 'bNan6blroq4BSkfMCqpmbCfK'
        self.secretKey = '50iNFlzPP3Y8RgVKhXOCqsup3DlGpOSz'
        self.client = AipNlp(self.appId, self.apiKey, self.secretKey)

    def post(self,request):
        title = request.data.get('title')
        content = request.data.get('content')
        dic = self.client.keyword(title, content)
        # data = json.dumps(dic, ensure_ascii=False, sort_keys=True, indent=4, separators=(',', ': '))
        data = json.dumps(dic,ensure_ascii=False)
        lst = json_decode(data)
        # lst = data.encode()
        print(data)
        tag =[]
        for i in lst['items']:
            tag.append(i)

        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':tag})





























































